package cn.source.system.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.model.H5LoginUser;
import cn.source.common.core.page.TableDataInfo;
import cn.source.system.asp.UserH5ContextHandler;
import cn.source.system.domain.*;
import cn.source.system.response.ApiGoodsInfoResponse;
import cn.source.system.response.ApiGoodsListResponse;
import cn.source.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chensl
 * @version 1.0.0
 * @ClassName ApiBannerController.java
 * @Description
 * @createTime 2023/8/5 19:40
 */
@RestController
@RequestMapping("/api/goods")
public class ApiGoodsController extends BaseController {

    @Autowired
    private IAaGoodsService aaGoodsService;

    @Autowired
    private IAaOrderService aaOrderService;

    @Autowired
    private IAaUserService aaUserService;

    @Autowired
    private IAaUserDownService aaUserDownService;

    @Autowired
    private IAaUserIntegralRecordService aaUserIntegralRecordService;

    /**
     * 根据一级分类ID获取二级分类
     * @return
     */
    @GetMapping("/goodsList")
    public TableDataInfo goodsList(Long id)
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();
        //获取用户已经下载的数据
        List<String> addOrders = aaOrderService.mapByUserId(loginUser.getUserId());
        startPage();
        //查询用户已经购买的视频ID
        //分页查询分类数据
        List<AaGoods> list = aaGoodsService.queryListByCategoryId(id , loginUser.getUserId());

        List<ApiGoodsListResponse> returnList = list.stream().map(m->{
            ApiGoodsListResponse response = new ApiGoodsListResponse();
            BeanUtil.copyProperties(m , response);
            if(addOrders != null && addOrders.contains(String.valueOf(m.getId()))){
                response.setAddStatus(1);
            }
            return response;
        }).collect(Collectors.toList());

        return getDataTable(returnList);
    }

    @GetMapping("/info")
    public AjaxResult info(Long id)
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();

        AaGoods goods = aaGoodsService.selectAaGoodsById(id);
        if(goods != null){
            Long addNum = aaOrderService.countByUserIdAndGoodsId(loginUser.getUserId() , id);

            //
            ApiGoodsInfoResponse infoResponse = BeanUtil.copyProperties(goods , ApiGoodsInfoResponse.class);
            if(addNum == null || addNum < 1){
                infoResponse.setGoodsDesc("");
                infoResponse.setGoodsVideo("");
                infoResponse.setAddStatus(0);
            }else{
                infoResponse.setAddStatus(1);
            }
            return AjaxResult.success(infoResponse);
        }

        return AjaxResult.success(null);
    }

    @GetMapping("/down")
    public AjaxResult down(Long id){
        H5LoginUser loginUser = UserH5ContextHandler.get();
        AaUserDown aaUserDown = new AaUserDown();
        aaUserDown.setGoodsId(id);
        aaUserDown.setUserId(loginUser.getUserId());
        aaUserDownService.insertAaUserDown(aaUserDown);
        return AjaxResult.success();
    }

    @GetMapping("/saveOrder")
    public AjaxResult saveOrder(Long id){
        H5LoginUser loginUser = UserH5ContextHandler.get();
        AaGoods goods = aaGoodsService.selectAaGoodsById(id);
        if(goods == null){
            return AjaxResult.error("商品不存在");
        }
        //判断等级或者积分
        AaUser aaUser = aaUserService.selectAaUserById(loginUser.getUserId());
        if(aaUser == null){
            return AjaxResult.error("账号异常");
        }
        if(aaUser.getUserStatus() != 0){
            return AjaxResult.error("账号已经冻结");
        }
        //查看等级
        if(goods.getUserLevel() != null && goods.getUserLevel() > aaUser.getUserLevel()){
            return AjaxResult.error("等级不足");
        }
        if(aaUser.getUserIntegral().intValue() < goods.getGoodsIntegral().intValue()){
            return AjaxResult.error("积分不足");
        }

        //查看是否已经兑换
        Long gNum = aaOrderService.countByUserIdAndGoodsId(null , id);
        if(gNum > 0){
            return AjaxResult.error("下手慢了，已经被兑换了，请刷新页面把");
        }

        AaOrder order = new AaOrder();
        order.setOrderCode(orderNo());
        order.setUserId(aaUser.getId());
        order.setGoodsId(goods.getId());
        order.setGoodsImage(goods.getGoodsImage());
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsIntegral(goods.getGoodsIntegral());
        order.setCreateTime(new Date());
        order.setUserName(aaUser.getUserName());

        //添加积分记录
        AaUserIntegralRecord record = new AaUserIntegralRecord();
        record.setUserId(order.getUserId());
        record.setIntegral(order.getGoodsIntegral());
        record.setType(2);
        record.setRecordDesc(goods.getGoodsName());
        record.setCreateDate(order.getCreateTime());

        aaOrderService.addUserOrder(order , record);
        return AjaxResult.success();
    }

    public static String orderNo() {
        return DateUtil.format(new Date() , DatePattern.PURE_DATE_PATTERN + getRandomNum(1000 , 9999));
    }

    public static int getRandomNum(int num1, int num2) {
        int result = (int) (num1 + Math.random() * (num2 - num1 + 1));
        return result;
    }


    /**
     * 订单记录
     * @return
     */
    @GetMapping("/orderList")
    public TableDataInfo orderList()
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();
        //获取用户已经下载的数据
        startPage();
        //查询用户已经购买的视频ID
        //分页查询分类数据
        AaOrder param = new AaOrder();
        param.setUserId(loginUser.getUserId());
        List<AaOrder> list = aaOrderService.selectAaOrderList(param);
        return getDataTable(list);
    }


    /**
     * 积分记录
     * @return
     */
    @GetMapping("/recordList")
    public TableDataInfo recordList()
    {
        H5LoginUser loginUser = UserH5ContextHandler.get();
        //获取用户已经下载的数据
        startPage();
        //查询用户已经购买的视频ID
        //分页查询分类数据
        AaUserIntegralRecord param = new AaUserIntegralRecord();
        param.setUserId(loginUser.getUserId());
        List<AaUserIntegralRecord> list = aaUserIntegralRecordService.selectAaUserIntegralRecordList(param);
        return getDataTable(list);
    }

    @GetMapping("/downOver")
    public void downOver(Long id){
        AaGoods goods = aaGoodsService.selectAaGoodsById(id);
        if(goods == null){
            return;
        }
        goods.setDownStatus(1);
        aaGoodsService.updateAaGoods(goods);
    }
}
